package main

import (
	"encoding/json"
	"fmt"
	"log"
	"math"
	"net/http"
	// 假设你将data_judge_module.go放在datajudge包中
	// "your-project/datajudge"
)

// 接收数据的结构体（与数据产生器发送的格式对应）
type ReceivedSensorData struct {
	DeviceID  string              `json:"device_id"`
	Timestamp int64               `json:"timestamp"`
	Data      map[string]float64  `json:"data"` // 传感器数据
	Meta      map[string]MetaInfo `json:"meta"` // μ和σ元数据
	Signature string              `json:"signature"`
}

// μ和σ信息结构体（与datajudge包中的MetaInfo相同）
type MetaInfo struct {
	Mu    float64 `json:"mu"`    // 均值
	Sigma float64 `json:"sigma"` // 标准差
}

// 方案1: 最简单的使用方式 - 只判断单个参数
func HandleDataUploadSimple(w http.ResponseWriter, r *http.Request) {
	var receivedData ReceivedSensorData

	// 解析JSON数据
	if err := json.NewDecoder(r.Body).Decode(&receivedData); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	// 逐个检查每个参数的状态
	fmt.Printf("设备 %s 的数据分析:\n", receivedData.DeviceID)

	for paramName, value := range receivedData.Data {
		if metaInfo, exists := receivedData.Meta[paramName]; exists {
			// 调用判断函数 - 这就是核心调用方式
			status := JudgeDataStatus(value, metaInfo.Mu, metaInfo.Sigma)

			fmt.Printf("  %s: %.4f -> %s\n", paramName, value, status)

			// 根据状态进行不同处理
			switch status {
			case "normal":
				// 正常数据的处理逻辑
				log.Printf("参数 %s 数据正常", paramName)
			case "abnormal":
				// 异常数据的处理逻辑（警告）
				log.Printf("警告: 参数 %s 数据异常，值=%f", paramName, value)
			case "error":
				// 错误数据的处理逻辑（报错）
				log.Printf("错误: 参数 %s 数据严重异常，值=%f", paramName, value)
			}
		}
	}

	// 返回成功响应
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

// 方案2: 完整的使用方式 - 批量分析并返回详细结果
func HandleDataUploadComplete(w http.ResponseWriter, r *http.Request) {
	var receivedData ReceivedSensorData

	// 解析JSON数据
	if err := json.NewDecoder(r.Body).Decode(&receivedData); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	// 转换meta格式以匹配datajudge包的需求
	metaForAnalysis := make(map[string]datajudge.MetaInfo)
	for param, meta := range receivedData.Meta {
		metaForAnalysis[param] = datajudge.MetaInfo{
			Mu:    meta.Mu,
			Sigma: meta.Sigma,
		}
	}

	// 批量分析所有参数 - 这是最便捷的调用方式
	analysisResults := datajudge.AnalyzeMultipleParameters(receivedData.Data, metaForAnalysis)

	// 获取统计信息
	stats := datajudge.GetStatusStatistics(analysisResults)

	// 检查是否有问题数据
	hasAbnormal := datajudge.HasAbnormalData(analysisResults)
	hasError := datajudge.HasErrorData(analysisResults)

	// 打印分析结果
	fmt.Printf("设备 %s 数据分析完成:\n", receivedData.DeviceID)
	fmt.Printf("  统计: 总计%d个参数，正常%d个，异常%d个，错误%d个\n",
		stats.Total, stats.Normal, stats.Abnormal, stats.Error)

	for param, result := range analysisResults {
		fmt.Printf("  %s: %.4f (%.2fσ偏差) -> %s\n",
			param, result.Value, result.Deviation, result.Status)
	}

	// 构造响应
	response := map[string]interface{}{
		"status":       "success",
		"device_id":    receivedData.DeviceID,
		"timestamp":    receivedData.Timestamp,
		"analysis":     analysisResults,
		"statistics":   stats,
		"has_abnormal": hasAbnormal,
		"has_error":    hasError,
	}

	// 根据数据质量设置HTTP状态码
	statusCode := http.StatusOK
	if hasError {
		statusCode = http.StatusUnprocessableEntity // 422
		response["message"] = "检测到错误数据"
	} else if hasAbnormal {
		statusCode = http.StatusAccepted // 202
		response["message"] = "检测到异常数据"
	} else {
		response["message"] = "所有数据正常"
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(response)
}

// 方案3: 自定义处理逻辑 - 针对特定参数的特殊处理
func HandleDataUploadCustom(w http.ResponseWriter, r *http.Request) {
	var receivedData ReceivedSensorData

	if err := json.NewDecoder(r.Body).Decode(&receivedData); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	// 重点关注的参数列表
	criticalParams := []string{"temperature", "humidity", "pm2_5", "ozone"}

	alertMessages := []string{}

	for _, paramName := range criticalParams {
		if value, exists := receivedData.Data[paramName]; exists {
			if metaInfo, metaExists := receivedData.Meta[paramName]; metaExists {

				// 分析单个参数 - 获取详细信息
				result := datajudge.AnalyzeSingleParameter(value, metaInfo.Mu, metaInfo.Sigma)

				// 针对不同参数的特殊处理逻辑
				switch paramName {
				case "temperature":
					if result.Status == datajudge.StatusError {
						alertMessages = append(alertMessages,
							fmt.Sprintf("温度严重异常: %.2f°C (偏差%.1fσ)", value, result.Deviation))
					}
				case "pm2_5":
					if result.Status == datajudge.StatusAbnormal || result.Status == datajudge.StatusError {
						alertMessages = append(alertMessages,
							fmt.Sprintf("PM2.5超标: %.2f μg/m³ (偏差%.1fσ)", value, result.Deviation))
					}
				case "ozone":
					if result.Status == datajudge.StatusError {
						alertMessages = append(alertMessages,
							fmt.Sprintf("臭氧浓度危险: %.4f ppb (偏差%.1fσ)", value, result.Deviation))
					}
				}
			}
		}
	}

	// 如果有警报，发送通知或记录日志
	if len(alertMessages) > 0 {
		log.Printf("设备 %s 检测到%d个警报:", receivedData.DeviceID, len(alertMessages))
		for _, msg := range alertMessages {
			log.Printf("  - %s", msg)
		}

		// 这里可以集成发送邮件、短信、推送通知等功能
		// sendAlert(receivedData.DeviceID, alertMessages)
	}

	// 返回响应
	response := map[string]interface{}{
		"status":      "success",
		"device_id":   receivedData.DeviceID,
		"alerts":      alertMessages,
		"alert_count": len(alertMessages),
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

func main() {
	// 根据需要选择合适的处理方式
	http.HandleFunc("/data/upload/simple", HandleDataUploadSimple)     // 最简单
	http.HandleFunc("/data/upload/complete", HandleDataUploadComplete) // 最完整
	http.HandleFunc("/data/upload/custom", HandleDataUploadCustom)     // 自定义

	fmt.Println("Go后端服务器启动在 :5000")
	fmt.Println("数据状态判断功能已集成")
	fmt.Println("可用端点:")
	fmt.Println("  /data/upload/simple   - 简单判断")
	fmt.Println("  /data/upload/complete - 完整分析")
	fmt.Println("  /data/upload/custom   - 自定义处理")

	log.Fatal(http.ListenAndServe(":5000", nil))
}

// ===== 以下是datajudge包的函数，实际使用时应该import包 =====

type DataStatus string

const (
	StatusNormal   DataStatus = "normal"
	StatusAbnormal DataStatus = "abnormal"
	StatusError    DataStatus = "error"
)

// 核心判断函数 - 这是后端开发者最常用的函数
func JudgeDataStatus(value, mu, sigma float64) DataStatus {
	if sigma == 0 {
		return StatusNormal
	}

	deviation := math.Abs(value-mu) / sigma

	if deviation <= 1.5 {
		return StatusNormal
	} else if deviation <= 3.0 {
		return StatusAbnormal
	} else {
		return StatusError
	}
}
